import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Host } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Subscription } from "rxjs";
import { AppComponent } from "../../../../../app.component";
import { BaseComponent } from "../../../../../shared/components/baseComponent/base.component";
import { LinearChartData } from '../../../../../shared/directives/charts/models/linearChart.model';
import { GoogleAnalyticsBeacon } from "../../../../../shared/models/googleAnalytics.model";
import { IssueType } from "../../../../../shared/models/issue.enum";
import { AnalyticsService } from "../../../../../shared/services/googleAnalytics.service";
import { UtilsService } from "../../../../../shared/services/utils.service";
import { CompanyService } from "../../company.service";
import { CompanyEsgService } from "../companyEsg.service";
import { EsgHistoricalPerformanceSummary, HistoricalPerformance } from '../summary/models/esgHistoricalPerformanceSummary.model';
import { EsgRpIndicatorCluster } from "./models/esgRpIndicatorCluster.model";
import { EsgThemeOverallPerformanceSummary } from "./models/esgThemeOverallPerformanceSummary.model";

/**
 * Company ESG Issue component
 *
 * Author: Sorin Spiru
 * Date: 22.03.2018
 */
@Component({
    templateUrl: 'esgIssue.component.html',
    styleUrls: ['../../company.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class EsgIssueComponent extends BaseComponent {
    private sub: Subscription;
    public formatIssueWeight: Function = UtilsService.formatIssueWeight;
    public companyId: string;
    public theme: IssueType;
    public performanceSummary: EsgThemeOverallPerformanceSummary;
    public clusters: EsgRpIndicatorCluster[];
    public overallChartData: LinearChartData[];
    public esgHistoricalPerformanceSummary: EsgHistoricalPerformanceSummary;

    constructor(
        @Host() private rootComponent: AppComponent,
        private route: ActivatedRoute,
        private cdRef: ChangeDetectorRef,
        private companyService: CompanyService,
        protected companyEsgService: CompanyEsgService,
        private analyticsService: AnalyticsService) {
        super(cdRef);
    }

    ngOnInit() {
        this.sub = this.route.data.subscribe(data => {
            this.theme = data['theme'];
            this.companyService.company.subscribe(company => {
                this.companyId = company.id;
                this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESGRatingTheme', 'Research', { CompanyId: company.id, ThemeName: IssueType[this.theme] }));
                this.companyEsgService.getEsgHistoricalPerformanceSummary(company.id)
                    .subscribe(performanceSummary => {
                        this.esgHistoricalPerformanceSummary = performanceSummary;
                        const chartTheme = this.theme === 1 ? 'environment' : (this.theme === 2 ? 'social' : 'governance');
                        this.overallChartData = this.getDataForChart(this.esgHistoricalPerformanceSummary[chartTheme]);
                        this.cdRef.markForCheck();
                    });

                this.companyEsgService.getEsgThemeOverallPerformanceSummary(company.id, this.theme).subscribe(data => {
                    this.performanceSummary = data;
                    this.cdRef.markForCheck();
                    this.rootComponent.finishLoading();
                }, error => this.errorCallback(_ => { this.performanceSummary = undefined; }, error));

                this.companyEsgService.getEsgRpIndicatorCluster(this.theme).subscribe(clusters => {
                    this.clusters = clusters;
                    this.cdRef.markForCheck();
                }, error => this.errorCallback(_ => { this.clusters = undefined; }, error));
            });
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    public getPercentileOrdinal(): string {
        return UtilsService.getOrdinalNameEnd(this.performanceSummary.percentile.comparativeGroupPercentileRank);
    }

    private getDataForChart(historicalPerformance: HistoricalPerformance): LinearChartData[] {
        return historicalPerformance.companyHistory.map((companyHistory, index) => {
            return {
                scoreCompany: companyHistory.score,
                date: companyHistory.date,
                scoreIndustryLead: historicalPerformance.industryLeaderHistory[index].score,
                scoreGrouptAvg: historicalPerformance.peerGroupAvgHistory[index].score
            };
        });
    }
}
